package cn.basic.auth.service.impl;

import cn.basic.auth.domain.Permission;
import cn.basic.auth.domain.Role;
import cn.basic.auth.mapper.RoleMapper;
import cn.basic.auth.vo.query.RoleAuthQuery;
import cn.basic.auth.vo.query.RoleMenuQuery;
import cn.basic.auth.vo.query.RoleQuery;
import cn.basic.auth.service.IRoleService;
import cn.basic.auth.vo.result.RoleVo;
import cn.basic.common.service.impl.IBaseServiceImpl;
import cn.basic.utils.AjaxResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * 角色--service层impl实现类
 * @date: 2023/3/6 14:02
 * @author: ZhaoLc
 * @version: 1.0
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class IRoleServiceImpl extends IBaseServiceImpl<Role,RoleQuery, RoleVo> implements IRoleService  {

    @Resource
    RoleMapper roleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBatch(RoleAuthQuery roleAuthQuery) {
        roleMapper.insertBatch(roleAuthQuery.getIds(),roleAuthQuery.getRoleId());
    }

    @Transactional(rollbackFor = Exception.class)
    public AjaxResult granted(RoleAuthQuery roleAuthQuery){
        // 如果设置的权限》0
        if (roleAuthQuery.getIds().size() != 0){
            // 补全sn
            List<Permission> permissions = getSnById(roleAuthQuery.getIds());
            roleAuthQuery.setIds(permissions);
            if (permissions.size()==0){
                // 后台重启后，前后端的ID不一致，防止报错提示重试！
                return AjaxResult.me().setMessage("网络波动！请重试！").setSuccess(false);
            }
            // 删除后全量增加
            roleMapper.deletePermissionById(roleAuthQuery.getRoleId());
            addBatch(roleAuthQuery);
        } else {
            // 如果传进来空的，就删除这个人的所有权限
            roleMapper.deletePermissionById(roleAuthQuery.getRoleId());
        }
        return AjaxResult.me();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult grantedMenus(RoleMenuQuery roleMenuQuery) {
        // 删除后 全量增加
        if(roleMenuQuery.getIds().size()>0) {
            roleMapper.deleteMenusById(roleMenuQuery.getRoleId());
            roleMapper.grantedMenus(roleMenuQuery.getIds(),roleMenuQuery.getRoleId());
        } else {
            roleMapper.deleteMenusById(roleMenuQuery.getRoleId());
        }
        return AjaxResult.me();
    }

    @Override
    public List<Permission> getSnById(List<Permission> permissions) {
        return roleMapper.getSnById(permissions);
    }
}
